package com.chj.comp.common.gateway.security.filter;

import com.alibaba.fastjson.JSONArray;
import com.chj.comp.common.core.util.Result;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Description: 全局过滤器(token校验)
 * @Author: cuihui
 * @Date: 2022/02/10
 */
@Component
@RefreshScope
@Slf4j
@ConfigurationProperties(prefix = "security.config", ignoreInvalidFields = true)
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private TokenStore tokenStore;

    /**
     * 放行url
     * @Value不能直接给list赋值，使用@ConfigurationProperties，需要给注入的字段添加setter方法
     */
    @Setter
    private List<String> ignoreUrls;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("-----校验token-----");
        String requestUrl = exchange.getRequest().getPath().value();
        AntPathMatcher pathMatcher = new AntPathMatcher();
        //1 放行接口（配置文件中读取放行url，此处不再写死）
        boolean match = ignoreUrls.stream().anyMatch(url -> pathMatcher.match(url, requestUrl));
        if (match){
            return chain.filter(exchange);
        }

//        // auth服务所有接口放行
//        if (pathMatcher.match("/comp/auth/**", requestUrl)) {
//            return chain.filter(exchange);
//        }
//        // swagger2接口放行
//        if (pathMatcher.match("/**/v2/api-docs", requestUrl)) {
//            return chain.filter(exchange);
//        }

        //2 检查token是否存在
        String token = getToken(exchange);
        if (StringUtils.isBlank(token)) {
            return noTokenMono(exchange);
        }
        //3 判断是否是有效的token
        OAuth2AccessToken oAuth2AccessToken;
        try {
            oAuth2AccessToken = tokenStore.readAccessToken(token);
            //4 判断token是否过期
            boolean expired = oAuth2AccessToken.isExpired();
            if(expired){
                return expireTokenMono(exchange);
            }
            return chain.filter(exchange);
        } catch (InvalidTokenException e) {
            log.info("无效的token: {}", token);
            return invalidTokenMono(exchange);
        }
    }

    /**
     * 获取token
     */
    private String getToken(ServerWebExchange exchange) {
        String tokenStr = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (StringUtils.isBlank(tokenStr)) {
            return null;
        }
        String token = tokenStr.split(" ")[1];
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return token;
    }

    /**
     * 无效的token
     */
    private Mono<Void> invalidTokenMono(ServerWebExchange exchange) {
        Result result = Result.failed("token无效");
        return buildReturnMono(result, exchange);
    }

    /**
     * 没有token
     * @param exchange
     * @return
     */
    private Mono<Void> noTokenMono(ServerWebExchange exchange) {
        Result result = Result.failed("token缺失");
        return buildReturnMono(result, exchange);
    }

    /**
     * 过期token
     * @param exchange
     * @return
     */
    private Mono<Void> expireTokenMono(ServerWebExchange exchange) {
        Result result = Result.failed("token过期");
        return buildReturnMono(result, exchange);
    }

    private Mono<Void> buildReturnMono(Result result, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        byte[] bits = JSONArray.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 10;
    }
}